package com.ambitor.ipro.service;

import java.util.Date;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.data.Parameter;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.app.gen.TaskGeneratorHelper;
import com.ambitor.ipro.entities.InstallSetting;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.entities.TradeState;
import com.ambitor.ipro.entities.TradeType;
import com.ambitor.ipro.entities.UninstallSetting;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.SkyenccUtil;
import com.ambitor.ipro.util.StringUtil;
import com.ambitor.ipro.util.TableName;

public class InstallService extends BaseService {

	private TopService topService = null;

	public InstallService(SuperDao superDao) {
		super(superDao);
		topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IPROMOTION, Constants.APP_SECRET_IPROMOTION);
	}

	@SuppressWarnings("unchecked")
	public IData saveUserPro(IData userPro) throws Exception {
		try {
			Date now = new Date();
			String nowStr = SkyenccUtil.formatDate(now);
			String nextExecDateStr = SkyenccUtil.getNextInstallDate(now,
					userPro.getInt("FREQUENCY"));
			userPro.put("START_TIME", nowStr);
			userPro.put("NEXT_EXEC_TIME", nextExecDateStr);
			userPro.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset oldUserPros = queryPreviousUserPro(userPro);
			if (oldUserPros.size() > 0) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < oldUserPros.size(); i++) {
					if (i <= 5) {
						sb.append(oldUserPros.getData(i).getString("PRO_ID"));
						sb.append(",");
					} else {
						sb.append("...");
						break;
					}
				}
				String oldSettings = StringUtil.trimSuffix(sb.toString(), ",");
				userPro.put("OLD_PRO_ID", oldSettings);
			}
			String proId = superDao.insertAndReturnLastInsertId(
					"TF_P_USER_PRO_BATCH", userPro);
			userPro.put("PRO_ID", proId);

			updatePreviousUserProAndUnintall(oldUserPros, userPro);
			saveUserProSub(userPro);
			return userPro;
		} catch (Exception e) {
			logger.error(userPro.getString("NICK") + "在保存推广设置时发生异常", e);
			throw new Exception("在保存推广设置时发生错误导致安装失败，请联系管理员");
		}
	}

	@SuppressWarnings("unchecked")
	private IDataset queryPreviousUserPro(IData proSetting) throws Exception {
		IData param = new DataMap();
		param.put("NEW_SETTING", proSetting.getString("INSTALL_SETTING"));
		String sql = "select OLD_SETTING from TD_P_PRO_LIMIT where NEW_SETTING =:NEW_SETTING"
				+ " and RESULT in(1,2)";
		IDataset dataset = superDao.queryListBySql(sql, param);
		if (dataset.size() == 0) {
			return dataset;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < dataset.size(); i++) {
			sb.append("'");
			sb.append(dataset.getData(i).getString("OLD_SETTING"));
			sb.append("'");
			sb.append(",");
		}
		String oldSettings = StringUtil.trimSuffix(sb.toString(), ",");
		param.clear();
		param.put("USER_ID", proSetting.getString("USER_ID"));
		param.put("VALID_FLAG", Constants.FLAG_YES);
		param.put("INSTALL_PLACE", proSetting.getString("INSTALL_PLACE"));
		sql = "select * from tf_p_user_pro_batch where user_id = :USER_ID "
				+ "and valid_flag =:VALID_FLAG and install_place = :INSTALL_PLACE "
				+ "and install_setting in(" + oldSettings
				+ ") and frequency > 0";
		dataset = superDao.queryListBySql(sql, param);
		return dataset;
	}

	@SuppressWarnings("unchecked")
	public String saveUserStyle(IData userStyle) throws Exception {
		String styleId = null;
		try {
			IDataset dataset = superDao.queryList(TableName.TF_P_USER_STYLE,
					userStyle);
			if (dataset.size() == 0) {
				styleId = superDao.insertAndReturnLastInsertId(
						TableName.TF_P_USER_STYLE, userStyle);
			} else {
				styleId = dataset.get(0, "STYLE_ID").toString();
			}
		} catch (Exception e) {
			String nick = userStyle.getString("NICK");
			logger.error(nick + "在保存样式的时候发生异常,信息为:", e);
			throw new Exception("保存样式发生异常，请联系管理员。");
		}
		return styleId;
	}

	@SuppressWarnings("unchecked")
	private void updatePreviousUserProAndUnintall(IDataset oldUserPros,
			IData proSetting) throws Exception {
		// String installSetting = proSetting.getString("INSTALL_SETTING");
		// boolean needUninstall = true;
		// if (InstallSetting.all.toString().equalsIgnoreCase(installSetting)
		// || InstallSetting.onSale.toString().equalsIgnoreCase(
		// installSetting)) {
		// needUninstall = false;
		// }
		for (int i = 0; i < oldUserPros.size(); i++) {
			IData oldPro = oldUserPros.getData(i);
			overridePreviousUserPro(proSetting, oldPro);
			// if (needUninstall) {
			// addOverrideUninstallTask(proSetting, oldProId);
			// }
		}
	}

	@SuppressWarnings("unchecked")
	private void overridePreviousUserPro(IData newProSetting,
			IData oldProSetting) throws Exception {
		String oldProId = oldProSetting.getString("PRO_ID");
		if (InstallSetting.someCategory.toString().equals(
				newProSetting.getString("INSTALL_SETTING"))
				&& InstallSetting.someCategory.toString().equals(
						oldProSetting.getString("INSTALL_SETTING"))) {
			String sql = "delete from tf_p_user_pro_sub where pro_id =:PRO_ID "
					+ "and CID in (" + newProSetting.getString("CATEGORIES")
					+ ") and valid_flag = 1";
			IData param = new DataMap();
			param.put("PRO_ID", oldProId);
			baseDao.executeUpdate(sql, param);
			param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset dataset = superDao.queryList("tf_p_user_pro_sub", param);
			if (dataset.size() > 0) {// 加入还存在生效的子分类就仍让规则生效
				return;
			}
		} else if (InstallSetting.itemCategory.toString().equals(
				newProSetting.getString("INSTALL_SETTING"))
				&& InstallSetting.itemCategory.toString().equals(
						oldProSetting.getString("INSTALL_SETTING"))) {
			String sql = "delete from tf_p_user_pro_sub where pro_id =:PRO_ID "
					+ "and CID in ("
					+ newProSetting.getString("ITEM_CATEGORIES")
					+ ") and valid_flag = 1";
			IData param = new DataMap();
			param.put("PRO_ID", oldProId);
			baseDao.executeUpdate(sql, param);
			param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset dataset = superDao.queryList("tf_p_user_pro_sub", param);
			if (dataset.size() > 0) {// 加入还存在生效的子分类就仍让规则生效
				return;
			}
		} else if (InstallSetting.custom.toString().equals(
				newProSetting.getString("INSTALL_SETTING"))
				&& InstallSetting.custom.toString().equals(
						oldProSetting.getString("INSTALL_SETTING"))) {
			String sql = "delete from tf_p_user_pro_sub where pro_id = :PRO_ID "
					+ "and IID in ("
					+ newProSetting.getString("INSTALL_IIDS")
					+ ") and valid_flag = 1";
			IData param = new DataMap();
			param.put("PRO_ID", oldProId);
			baseDao.executeUpdate(sql, param);
			param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset dataset = superDao.queryList("tf_p_user_pro_sub", param);
			if (dataset.size() > 0) {// 加入还存在生效的宝贝就仍让规则生效
				return;
			}
		}
		String sql = "delete from tf_p_user_pro_batch  where pro_id = ?";
		Parameter parameter = new Parameter();
		parameter.add(oldProId);
		baseDao.executeUpdate(sql, parameter);
	}

	/**
	 * 暂时没有使用
	 */
	@SuppressWarnings("unchecked")
	protected void addOverrideUninstallTask(IData proSetting, String oldProId)
			throws Exception {
		IData tradeProBatch = new DataMap();
		tradeProBatch.put("TRADE_STATE", TradeState.UN_EXECUTE);// 未执行
		tradeProBatch.put("TRADE_TYPE", TradeType.OVERRIDE_UNINSTALL);// 覆盖卸载
		tradeProBatch.put("USER_ID", proSetting.getString("USER_ID"));
		tradeProBatch.put("NICK", proSetting.getString("NICK"));
		tradeProBatch.put("CREATE_TIME", proSetting.getString("START_TIME"));
		tradeProBatch.put("PLAN_EXEC_TIME", proSetting.getString("START_TIME"));
		tradeProBatch.put("PRIORITY", Constants.HIGH_PRIORITY);
		tradeProBatch
				.put("UNINSTALL_SETTING", UninstallSetting.BATCH_UNINSTALL);
		tradeProBatch.put("PRO_ID", oldProId);
		tradeProBatch.put("PLACE", proSetting.getString("INSTALL_PLACE"));
		tradeProBatch.put("REMARK", "覆盖卸载");
		TaskGeneratorHelper.addTask(superDao, tradeProBatch);
	}

	@SuppressWarnings("unchecked")
	private void saveUserProSub(IData userPro) throws Exception {
		IDataset userProSubList = new DatasetList();
		String intalllSetting = userPro.getString("INSTALL_SETTING");
		if ("custom".equalsIgnoreCase(intalllSetting)) {
			String installIids = userPro.getString("INSTALL_IIDS");
			String[] installIidArray = installIids.split(",");
			for (String iid : installIidArray) {
				IData userProSub = new DataMap();
				userProSub.put("PRO_ID", userPro.getString("PRO_ID"));
				userProSub.put("USER_ID", userPro.getString("USER_ID"));
				userProSub.put("IID", iid);
				userProSub.put("VALLD_FLAG", Constants.FLAG_YES);
				userProSubList.add(userProSub);
			}
			superDao.insert("TF_P_USER_PRO_SUB", userProSubList);
		} else if ("someCategory".equalsIgnoreCase(intalllSetting)) {
			String installCids = userPro.getString("CATEGORIES");
			String[] installCidArray = installCids.split(",");
			for (String cid : installCidArray) {
				IData userProSub = new DataMap();
				userProSub.put("PRO_ID", userPro.getString("PRO_ID"));
				userProSub.put("USER_ID", userPro.getString("USER_ID"));
				userProSub.put("CID", cid);
				userProSub.put("VALLD_FLAG", Constants.FLAG_YES);
				userProSubList.add(userProSub);
			}
			superDao.insert("TF_P_USER_PRO_SUB", userProSubList);
		} else if ("itemCategory".equalsIgnoreCase(intalllSetting)) {
			String installCids = userPro.getString("ITEM_CATEGORIES");
			String[] installCidArray = installCids.split(",");
			for (String cid : installCidArray) {
				IData userProSub = new DataMap();
				userProSub.put("PRO_ID", userPro.getString("PRO_ID"));
				userProSub.put("USER_ID", userPro.getString("USER_ID"));
				userProSub.put("CID", cid);
				userProSub.put("VALLD_FLAG", Constants.FLAG_YES);
				userProSubList.add(userProSub);
			}
			superDao.insert("TF_P_USER_PRO_SUB", userProSubList);
		}
	}

	/**
	 * 安装统计代码
	 */
	@SuppressWarnings("unchecked")
	public void installCount(IData userSession, Result versionInfo) {
		if (versionInfo.getCode() <= 1) {
			return;
		}
		try {
			userSession = superDao.queryByPK(TableName.TF_P_USER_SESSION,
					userSession);
		} catch (Exception e) {
			logger.warn("", e);
		}
		String countFlag = userSession.getString("INSTALL_COUNT_FLAG",
				Constants.FLAG_NO);
		if (userSession.size() > 0 && Constants.FLAG_NO.equals(countFlag)) {
			try {
				topService.installCount(userSession.getString("SESSION_ID"),
						userSession.getString("USER_ID"), userSession
								.getString("NICK"));
				IData param = new DataMap();
				param.put("USER_ID", userSession.getString("USER_ID"));
				param.put("INSTALL_COUNT_FLAG", Constants.FLAG_YES);
				superDao.update(TableName.TF_P_USER_SESSION, param);
			} catch (Exception e) {
				logger.warn(e.toString());
			}
		}
	}

	@SuppressWarnings("unchecked")
	public String saveTrdeProBatch(IData userPro, String installlPlaces)
			throws Exception {
		IData tradeProBatch = new DataMap();
		tradeProBatch.put("USER_ID", userPro.getString("USER_ID"));
		tradeProBatch.put("NICK", userPro.getString("NICK"));
		tradeProBatch.put("TRADE_STATE", TradeState.UN_EXECUTE);// 未执行
		tradeProBatch.put("TRADE_TYPE", TradeType.INSTANT_INSTALL);// 立即安装
		tradeProBatch.put("PRO_ID", userPro.getString("PRO_ID"));
		tradeProBatch.put("PRIORITY", Constants.MIDDLE_PRIORITY);
		tradeProBatch.put("CREATE_TIME", userPro.getString("START_TIME"));
		tradeProBatch.put("PLAN_EXEC_TIME", userPro.getString("START_TIME"));
		tradeProBatch.put("PLACE", installlPlaces);
		tradeProBatch.put("REMARK", "立即安装");
		return TaskGeneratorHelper.addTask(superDao, tradeProBatch);
	}
}
